package com.mla.fastdfs.shiro;

import com.mla.fastdfs.commom.Result;
import com.mla.fastdfs.pojo.User;
import com.mla.fastdfs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取当前用户token
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User user = userService.getByName(userToken.getUsername());

        //如果用户不存在
        if (user == null)
            return null; //自动抛出UnknownAccountException

        if (!user.getStatus().equals(0))
            return null;

        //password siro处理 不交由用户处理
        return new SimpleAuthenticationInfo(user, user.getPassword(), user.getRealName());
    }
}
